/*
 * Copyright (c) 2006, 2007 Sun Microsystems, Inc.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package org.sunspotworld;

import com.sun.spot.peripheral.Spot;
import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.io.IScalarInput;
import com.sun.spot.sensorboard.peripheral.ISwitch;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.sensorboard.peripheral.LEDColor;
import com.sun.spot.util.*;
import java.io.IOException;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * The startApp method of this class is called by the VM to start the
 * application.
 *
 * The manifest specifies this class as MIDlet-1, which means it will
 * be selected for execution.
 */
public class StartApplication extends MIDlet {
    public static final int MAX_VOLTAGE_MILLIVOLTS = 3300;
    public static final int MAX_VALUE = 1023;
    public static final double GAUGE_FACTOR = 0.232;
    private static final int LED_STEP_VALUE = MAX_VOLTAGE_MILLIVOLTS / 8;
    private LEDColor displayColor = LEDColor.CYAN;
    private ITriColorLED [] leds = EDemoBoard.getInstance().getLEDs();
    private IScalarInput input = EDemoBoard.getInstance().getScalarInputs()[EDemoBoard.A0];
    
    /**
     * Reads scalar input on A0 and displays the value to the LEDs in terms of the MAX_VALUE field
     * Also, writes value to System.out
     */
    private void displayInput() {
        try {
            int value = input.getValue()*MAX_VOLTAGE_MILLIVOLTS/MAX_VALUE; //read scalar input value.  convert into millivolts
            System.out.println("Voltage: " + value + " mV");
            System.out.println("Strain: " + value * GAUGE_FACTOR + "\u03BC");
            //display value on LEDs
            for (int i=0; i<8; i++) {
                leds[i].setColor(displayColor);
                leds[i].setOn(value>i*LED_STEP_VALUE);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    protected void startApp() throws MIDletStateChangeException {
        System.out.println("Hello, world");
        new BootloaderListener().start();   // monitor the USB (if connected) and recognize commands from host

        long ourAddr = Spot.getInstance().getRadioPolicyManager().getIEEEAddress();
        System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));
        
        ISwitch sw1 = EDemoBoard.getInstance().getSwitches()[EDemoBoard.SW1];
        leds[0].setRGB(100,0,0);                // set color to moderate red
        while (sw1.isOpen()) {                  // done when switch is pressed
            displayInput();
            Utils.sleep(1000);                  // wait 1 second
        }
        notifyDestroyed();                      // cause the MIDlet to exit
    }
    
    protected void pauseApp() {
        // This is not currently called by the Squawk VM
    }
    
    /**
     * Called if the MIDlet is terminated by the system.
     * I.e. if startApp throws any exception other than MIDletStateChangeException,
     * if the isolate running the MIDlet is killed with Isolate.exit(), or
     * if VM.stopVM() is called.
     * 
     * It is not called if MIDlet.notifyDestroyed() was called.
     *
     * @param unconditional If true when this method is called, the MIDlet must
     *    cleanup and release all resources. If false the MIDlet may throw
     *    MIDletStateChangeException  to indicate it does not want to be destroyed
     *    at this time.
     */
    protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
        for (int i = 0; i < 8; i++) {
            leds[i].setOff();
        }
    }
}
